package common;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 实现接口的不同请求方法的调用
 * 
 * @author MaoJJ
 *
 */
public class Request
{
	/**
	 * 实现InputStream转换String
	 * 
	 * @param inputStream
	 *            - 需要转换的InputStream
	 * @return 转换后的String；如何转换失败则返回null
	 * @throws IOException
	 */
	private static String convertStreamToString(InputStream inputStream) throws IOException
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuffer sb = new StringBuffer();
		String Line = null;
		try
		{
			while ((Line = reader.readLine()) != null)
			{
				sb.append(Line);
			}
		}
		catch (IOException e)
		{
			// 转换失败，返回null
			reader.close();
			return null;
		}

		reader.close();
		// String ret = new String(sb.toString().getBytes("GBK"), "UTF-8");
		String ret = sb.toString();
		return ret;
	}

	/**
	 * 实现调用带Token的Get接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param parms
	 *            - 接口参数；如果无参数，传null
	 * @param token
	 *            - 调用接口时需要的Token
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String get(String url, Map<String, String> parms, String token) throws IOException
	{
		// 拼接URL与Get参数
		if (parms != null)
		{
			StringBuffer sbParms = new StringBuffer();
			for (String key : parms.keySet())
			{
				String parm = parms.get(key);
				if (parm != null)
				{
					if (sbParms.toString().isEmpty())
					{
						sbParms.append("?");
						sbParms.append(key);
						sbParms.append("=");
						sbParms.append(URLEncoder.encode(parm, "UTF-8"));

					}
					else
					{
						sbParms.append("&");
						sbParms.append(key);
						sbParms.append("=");
						sbParms.append(URLEncoder.encode(parm, "UTF-8"));
					}
				}

			}
			url = url + sbParms.toString();
		}

		// 建立HTTP连接
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();

		// HTTP头增加Token
		if (token != null)
		{
			connection.setRequestProperty("token", token);
		}

		// 设置超时间
		int time = Integer.parseInt(Config.getValue("Timeout", "time"));
		connection.setConnectTimeout(time * 1000);
		connection.setReadTimeout(time * 1000);

		// 调用接口并将其返回数据转换成String类型
		String result;
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			// 接口调用失败，返回null
			// e.printStackTrace();

			// MaoJJ-20170822-Add-S
			Log.write("接口=" + url + System.getProperty("line.separator") + "参数=" + parms
					+ System.getProperty("line.separator") + "错误码=" + e.getMessage());
			// MaoJJ-20170822-Add-E

			return null;
		}

		// 关闭HTTP连接
		connection.disconnect();
		return result;
	}

	/**
	 * 实现调用不带Token的Get接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param parms
	 *            - 接口参数；如果无参数，传null
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String get(String url, Map<String, String> parms) throws IOException
	{
		return get(url, parms, null);
	}

	/**
	 * 实现调用带Token的POST接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @param token
	 *            - 调用接口时需要的Token
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String post(String url, Object content, String token) throws IOException
	{
		// 建立HTTP连接
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setRequestMethod("POST");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		// 设置HTTP-Headers：Content-Type
		connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

		// 设置HTTP-Headers：Token
		if (token != null)
		{
			connection.setRequestProperty("Token", token);
		}

		// 设置超时间
		int time = Integer.parseInt(Config.getValue("Timeout", "time"));
		connection.setConnectTimeout(time * 1000);
		connection.setReadTimeout(time * 1000);

		// 设置HTTP-Content
		if (content != null)
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write(content.toString().getBytes("UTF-8"));
			out.flush();
			out.close();
		}
		else
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write("".getBytes("UTF-8"));
			out.flush();
			out.close();
		}

		// 调用接口，并将接口返回数据转换成String类型
		String result = null;
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			// 接口调用失败，返回null
			// e.printStackTrace();

			// MaoJJ-20170822-Add-S
			Log.write("接口=" + url + System.getProperty("line.separator") + "参数=" + content
					+ System.getProperty("line.separator") + "错误码=" + e.getMessage());
			// MaoJJ-20170822-Add-E

			return null;
		}

		// 关闭HTTP连接
		connection.disconnect();

		return result;
	}

	/**
	 * 实现调用不带Token的POST接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String post(String url, Object content) throws IOException
	{
		return post(url, content, null);
	}

	/**
	 * 实现调用带Token的Option接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param parms
	 *            - 接口参数；如果无参数，传null
	 * @param token
	 *            - 调用接口时需要的Token
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String options(String url, Map<String, String> parms, String token) throws IOException
	{
		// 拼接URL与Option参数
		if (parms != null)
		{
			StringBuffer sbParms = new StringBuffer();
			for (String key : parms.keySet())
			{
				String parm = parms.get(key);
				if (parm != null)
				{
					if (sbParms.toString().isEmpty())
					{
						sbParms.append("?");
						sbParms.append(key);
						sbParms.append("=");
						sbParms.append(URLEncoder.encode(parm, "UTF-8"));
					}
					else
					{
						sbParms.append("&");
						sbParms.append(key);
						sbParms.append("=");
						sbParms.append(URLEncoder.encode(parm, "UTF-8"));
					}
				}

			}
			url = url + sbParms.toString();
		}

		// 建立HTTP连接
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setRequestMethod("OPTIONS");

		// HTTP头增加Token
		if (token != null)
		{
			connection.setRequestProperty("token", token);
		}

		// 设置超时间为
		int time = Integer.parseInt(Config.getValue("Timeout", "time"));
		connection.setConnectTimeout(time * 1000);
		connection.setReadTimeout(time * 1000);

		// 调用接口并将其返回数据转换成String类型
		String result;
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			// 接口调用失败，返回null
			// e.printStackTrace();

			// MaoJJ-20170822-Add-S
			Log.write("接口=" + url + System.getProperty("line.separator") + "参数=" + parms
					+ System.getProperty("line.separator") + "错误码=" + e.getMessage());
			// MaoJJ-20170822-Add-E

			return null;
		}

		// 关闭HTTP连接
		connection.disconnect();
		return result;
	}

	/**
	 * 实现调用不带Token的Option接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param parms
	 *            - 接口参数；如果无参数，传null
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String options(String url, Map<String, String> parms) throws IOException
	{
		return options(url, parms, null);
	}

	/**
	 * 实现调用带Token的PUT接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @param token
	 *            - 调用接口时需要的Token
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String put(String url, Object content, String token) throws IOException
	{
		// 建立HTTP连接
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setRequestMethod("PUT");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		// 设置HTTP-Headers：Content-Type
		// connection.setRequestProperty("Content-Type",
		// "application/json;charset=utf-8");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		// 设置HTTP-Headers：Token
		if (token != null)
		{
			connection.setRequestProperty("Token", token);
		}

		// 设置超时间
		int time = Integer.parseInt(Config.getValue("Timeout", "time"));
		connection.setConnectTimeout(time * 1000);
		connection.setReadTimeout(time * 1000);

		// 设置HTTP-Content
		if (content != null)
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write(content.toString().getBytes("UTF-8"));
			out.flush();
			out.close();
		}
		else
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write("".getBytes("UTF-8"));
			out.flush();
			out.close();
		}

		// 调用接口，并将接口返回数据转换成String类型
		String result = null;
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			// 接口调用失败，返回null
			// e.printStackTrace();

			// MaoJJ-20170822-Add-S
			Log.write("接口=" + url + System.getProperty("line.separator") + "参数=" + content
					+ System.getProperty("line.separator") + "错误码=" + e.getMessage());
			// MaoJJ-20170822-Add-E

			return null;
		}

		// 关闭HTTP连接
		connection.disconnect();

		return result;
	}

	/**
	 * 实现调用不带Token的PUT接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String put(String url, Object content) throws IOException
	{
		return put(url, content, null);
	}

	/**
	 * 实现带Token的Delect接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @param token
	 *            - 调接口需要的Token
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String delete(String url, Object content, String token) throws IOException
	{
		// 建立HTTP连接
		URL postUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
		connection.setRequestMethod("DELETE");
		connection.setDoInput(true);
		connection.setDoOutput(true);

		// 设置HTTP-Headers：Content-Type
		connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

		// 设置HTTP-Headers：Token
		if (token != null)
		{
			connection.setRequestProperty("Token", token);
		}

		// 设置超时间
		int time = Integer.parseInt(Config.getValue("Timeout", "time"));
		connection.setConnectTimeout(time * 1000);
		connection.setReadTimeout(time * 1000);

		// 设置HTTP-Content
		if (content != null)
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write(content.toString().getBytes("UTF-8"));
			out.flush();
			out.close();
		}
		else
		{
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			out.write("".getBytes("UTF-8"));
			out.flush();
			out.close();
		}

		// 调用接口，并将接口返回数据转换成String类型
		String result = null;
		try
		{
			result = convertStreamToString(connection.getInputStream());
		}
		catch (IOException e)
		{
			// 接口调用失败，返回null
			// e.printStackTrace();

			// MaoJJ-20170822-Add-S
			Log.write("接口=" + url + System.getProperty("line.separator") + "参数=" + content
					+ System.getProperty("line.separator") + "错误码=" + e.getMessage());
			// MaoJJ-20170822-Add-E

			return null;
		}

		// 关闭HTTP连接
		connection.disconnect();

		return result;
	}

	/**
	 * 实现调用不带Token的DELETE接口
	 * 
	 * @param url
	 *            - 接口地址
	 * @param content
	 *            - 接口参数
	 * @return 接口返回数据；如果调用失败，返回null
	 * @throws IOException
	 */
	public static String delete(String url, Object content) throws IOException
	{
		return delete(url, content, null);
	}
}
